<?php
/**
 * 概要描述：
 * @author: 救火队队长
 * @since: 2020-03-11 9:46
 */

namespace app\common\controller;
use app\BaseController;
use app\common\model\ManageRoleOperationRel;
use app\common\model\Operation;
use app\common\model\OperationLog;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\facade\Log;
use think\facade\View;

class IndexController extends BaseController
{
    protected $user_id;
    protected $username;

    protected function initialize()
    {
        parent::initialize();

        //没有登陆，请先登录
        if (!session('?user')) {
            cookie('redirect_url', request()->url(true), 3600);
            return $this->redirect(url('/index/index'));
        }
        $this->user_id = session('user.id');
//        if($this->user_id != 1){
//            dd('系统维护中,预计需要30分钟...');
//        }
        $this->username = session('user.username');
        if(!$this->checkToken($this->user_id)){
            session('user' , null);
            session('user_token' , null);
            session('home_name' , null);
        }

        //获取改用户是否有message未查看
        $msg_look_count  = Db::name('message')->where("FIND_IN_SET({$this->user_id} , user_array)")->count();
        $msg_count       = Db::name('message')->count();

        $is_code         = Db::name('user')->where(['id'=>$this->user_id])->value('is_code');
        //公告列表
        $notice_list     = Db::name('notice')->order('ctime desc')->select()->toArray();
        $first_notice    ='';
        foreach ($notice_list as $k=>$v){
            $first_notice = $v['text'];
            break;
        }
        $list_tran_gun = Db::name('cards_trans')->alias('ct')
            ->leftJoin('user u','u.id=ct.user_id')
            ->field('u.username,ct.ctime,ct.amount_auth,ct.shopping')
            ->where("tran_status='Authorized' and reversal_flag='N'")
            ->limit(10)
            ->order('ct.ctime desc')
            ->select()
            ->toArray();
        $new_tran = [];
        if($list_tran_gun){
            foreach ($list_tran_gun as $k_gun=>&$v_gun){
                $shopping           = $v_gun['shopping'];
                $result_shopping    = 'CardEcho';
                if(!empty($shopping)){
                    $shopping_array = explode(' ',$shopping);
                    $result_shopping= $shopping_array[0];
                }
                $v_gun['shopping']  = $result_shopping;
                $v_gun['username'] = substr($v_gun['username'] , 0 ,4) . '****';
                $v_gun['amount_auth'] = '$' . $v_gun['amount_auth'];
                $v_gun['ctime']     = substr($v_gun['ctime'] , 11,5);
                if(strpos($result_shopping , 'PAYPAL') !== false
                    || strpos($result_shopping , 'PP') !== false ){
                }else{
                    $new_tran[] = $v_gun;
                }
            }
        }
        View::assign([
            'msg_state' => (($msg_count - $msg_look_count) >0)? 1:0,
            'home_name' => "CardEcho",
            'data_user' => session("user"),
            'server_weixin' => getSetting('server_weixin'),
            'server_email'  => getSetting('server_email'),
            'notice_list'   => $notice_list,
            'first_notice'  => $first_notice,
            'list_tran_gun' => $new_tran,
            'is_code'      => $is_code,
            'user_id'       => $this->user_id
        ]);
        View::layout('layout');
//        $this->record();
    }

    public function getCardSet($blog=true)
    {
        $list = Db::name('user_set')->where(['user_id' => $this->user_id])
            ->order('type')->find();
        if(empty($list)){
            $type  = Db::name('user')->where(['id' => $this->user_id])->value('grade');
            //grade = 2时候，是管理员认证用户， 那么user_set 中type=1就按用户认证状态算
            if($type == 2){
                $type =1;
            }
            $list = Db::name('user_set')->where(['type' => $type , 'user_id'=>0])->find();
        }
        $list_new =[];
        $list_new['max_card'] = $list['max_card'];
        $card_set = json_decode($list['card_set'] , true);
        if(!$blog){
            return $card_set;
        }
        if($card_set){
            foreach ($card_set as $k=>$v){
                $list_new[$v['bank_type']][$v['card_type']]['is_used'] = $v['is_used'];
                $list_new[$v['bank_type']][$v['card_type']]['rate_fund'] = $v['rate_fund'];
                $list_new[$v['bank_type']][$v['card_type']]['rate_refund'] = $v['rate_refund'];
                $list_new[$v['bank_type']][$v['card_type']]['rate_tran'] = $v['rate_tran'];
                $list_new[$v['bank_type']][$v['card_type']]['open_amount'] = $v['open_amount'];
            }
        }
        return $list_new;
    }

    public function checkToken($user_id)
    {
        $blog = true;

        $user_token_list = Db::name('user_token')
            ->where(['user_id'=>$user_id ])
            ->order("ctime desc")
            ->find();
        /**更新2024-07-23 修改**/
//        $current_ip    = ip();
//        $user_token_list = Db::name('user_token')
//            ->where(['user_id'=>$user_id , 'ip' => $current_ip])
//            ->order("ctime desc")
//            ->find();
        /**更新2022-03-23 原始**/
//        $user_token_list = Db::name('user_token')
//            ->where(['user_id'=>$user_id])
//            ->order("ctime desc")
//            ->find();
//        $sql_token = $user_token_list['token'];
//        //验证user_token是否不一致
//        if($sql_token != session('user_token')){
//            $blog = false;
//            return $blog;
//        }
        $sql_time    = $user_token_list['ctime'];
        $config_time = getSetting('user_login_expired_time'); //配置的过期时间
        $currect_time= getUtcTime();
        //验证时间是否过期
        if(($currect_time - $sql_time) > $config_time){
            $blog = false;
        }
        return $blog;
    }

    public function record()
    {
        $user       = session('user');
        if (request()->isPost()) {
            $ctl          = strtolower(request()->controller());
            $act          = strtolower(request()->action());
            $operation = new Operation();
            $opinfo    = $operation->getOperationInfo($ctl, $act, $operation::MENU_MANAGE);

            if ($opinfo['status']) {
                $postData = input('post.');
                $decs     = $opinfo['data']['act']['name'];
                $log      = [
                    'manage_id'  => $user['id'],
                    'controller' => $ctl,
                    'method'     => $act,
                    'desc'       => $decs,
                    'content'    => json_encode($postData),
                    'ip'         => get_client_ip(0,true),
                ];
                $logModel = new OperationLog();
                $logModel->doAdd($log);
            } else {
                Log::record(json_encode($opinfo));
            }
        }
    }

}